package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by 18702 on 2017/12/15.
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0){
            return ServerResponse.createByErrorOnMsg("用户名不存在");
        }

        //todo MD5 密码加密
        String MD5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,MD5Password);
        //程序到这  表示账号存在但是and条件匹配不成功  密码错误
        if(user == null){
            return ServerResponse.createByErrorOnMsg("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登陆成功",user);
    }

    public ServerResponse<String> register(User user){
        ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int count = userMapper.insert(user);
        if(count == 0){
            return ServerResponse.createByErrorOnMsg("注册失败");
        }
        return ServerResponse.createBySuccessOnMsg("注册成功");
    }

    //校验方法
    public ServerResponse<String> checkValid(String str ,String type){
        if(StringUtils.isNoneBlank(type)){
            //校验
            if(Const.USERNAME.equals(type)){
                int count = userMapper.checkUsername(str);
                if(count > 0){
                    return ServerResponse.createByErrorOnMsg("用户名已存在");
                }
            }

            if(Const.EMAIL.equals(type)){
                int count = userMapper.checkEmail(str);
                if(count > 0){
                    return ServerResponse.createByErrorOnMsg("邮箱已存在");
                }
            }
        }else {
            return ServerResponse.createByErrorOnMsg("参数错误");
        }
        return ServerResponse.createBySuccessOnMsg("教研成功");
    }

    public ServerResponse selectQuestion(String username){
        ServerResponse valid_response = this.checkValid(username,Const.USERNAME);
        if(valid_response.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorOnMsg("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorOnMsg("找回密码的问题为空");
    }

    public  ServerResponse<String> checkAnswer(String usernma ,String password , String answer){
        int i = userMapper.checkAnswer(usernma, password, answer);
        if(i > 0){
            //回答忘记密码答案正确
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+usernma,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorOnMsg("问题答案回答错误！");
    }


    public ServerResponse<String> forgetRestPassword(String username,String passwordNew,String forgetToken){
        if(StringUtils.isNotBlank(forgetToken)){
            return ServerResponse.createByErrorOnMsg("参数错误，token需要传递");
        }
        ServerResponse valid_response = this.checkValid(username,Const.USERNAME);
        if(valid_response.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorOnMsg("用户不存在");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isNotBlank(token)){
            return ServerResponse.createByErrorOnMsg("token无效或者过期");
        }
        if(StringUtils.equals(forgetToken,token)){
            String md5password = MD5Util.MD5EncodeUtf8(passwordNew);
            int count = userMapper.updatePasswordByUsername(username,md5password);

            if(count >0){
                return ServerResponse.createBySuccessOnMsg("修改密码成功");
            }
        }else{
            return ServerResponse.createByErrorOnMsg("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorOnMsg("修改密码失败");
    }

    public ServerResponse<String> resetPassword(String passowrdOld,String passwordNew,User user){
        //防止横向越权，要校验下这个用户的旧密码
        int count = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passowrdOld), user.getId());
        if(count == 0){
            ServerResponse.createByErrorOnMsg("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 0 ){
            ServerResponse.createBySuccessOnMsg("密码修改成功");
        }
        return ServerResponse.createByErrorOnMsg("密码修改失败");
    }

    public ServerResponse<User> updateInformation(User user){
        //防止横向越权，要校验下这个用户的邮箱
        int count = userMapper.checkEmailByUserId(user.getEmail(),user.getId());
        if(count == 0){
            ServerResponse.createByErrorOnMsg("邮箱已存在，请更改邮箱，在尝试更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        int updatecount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updatecount> 0 ){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorOnMsg("更新个人信息失败");
    }

    public ServerResponse<User> getinformation(int userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if( user == null){
            return ServerResponse.createByErrorOnMsg("用户不存在");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    /**
     * 校验是否有管理员权限
     * @param user
     * @return
     */
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }
  }
